package org.neuedu.fly.service;

import org.apache.ibatis.session.SqlSession;
import org.neuedu.fly.entity.Post;
import org.neuedu.fly.entity.User;
import org.neuedu.fly.entity.vo.ResponseEntity;
import org.neuedu.fly.mapper.*;
import org.neuedu.fly.util.FileUploadUtil;
import org.neuedu.fly.util.SqlSessionUtil;
import org.neuedu.fly.util.SysUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class UserService {
    private SqlSession session = null;
    private UserMapper userMapper = null;

    public ResponseEntity page(String page, String limit) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        int pageIndex = Integer.parseInt(page);
        int pageSize = Integer.parseInt(limit);
        pageIndex = (pageIndex - 1) * pageSize;
        List<User> data = userMapper.page(pageIndex,pageSize);
        long count = userMapper.userCount();
        return ResponseEntity.page(count, data);
    }

    public ResponseEntity findUser(int userId) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        User data = userMapper.findUserById(userId);
        return ResponseEntity.data(data);
    }

    public ResponseEntity checkedTel(String tel) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        boolean flg = userMapper.isUniqueTel(tel);
        if (flg) {
            return ResponseEntity.error("该手机号已经注册过了");
        }
        return ResponseEntity.ok();
    }


    public ResponseEntity register(User user) {
        boolean flg = false;
        try {
            session = SqlSessionUtil.getSqlSession();
            userMapper = session.getMapper(UserMapper.class);
            flg = userMapper.register(user);
            //一定注意要提交
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        if (flg) {
            return ResponseEntity.ok("注册成功！");
        }
        return ResponseEntity.error("注册失败！");
    }


    public ResponseEntity login(String tel, String pwd) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.login(tel, pwd);
        //用户名或密码是否输入正确
        if (Objects.isNull(user)) {
            return ResponseEntity.error("用户名或密码输入有误！");
        }
        //是否被禁用
        if (user.getUserStatus() == SysUtil.UserStatus.DISABELD) {
            return ResponseEntity.error("你已被禁用，请联系管理员!");
        }
        return ResponseEntity.data(user);
    }


    public ResponseEntity update(User newUser, HttpSession s) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        User user = (User) s.getAttribute(SysUtil.CURRENT_USER);
        if (Objects.nonNull(user))user.setNickName(newUser.getNickName());
        boolean flag = userMapper.edit(newUser);
        session.commit();
        if (flag == true)
            return ResponseEntity.ok("更新成功");
        else
            session.rollback();
        return ResponseEntity.error("出错了");
    }

    public ResponseEntity editPwd(int uId, String tel, String password, String nowpass) {
        session = SqlSessionUtil.getSqlSession();
        userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.login(tel, password);
        if (user != null) {
            User newUser = User.builder().id(uId).password(nowpass).build();
            boolean flag = userMapper.editPwd(newUser);
            session.commit();
            if (!flag) {
                session.rollback();
                return ResponseEntity.error("出错了");
            }
            return ResponseEntity.ok("密码修改成功");
        }
        return ResponseEntity.error("密码错误！");
    }

    public ResponseEntity del(int uId) {
        session = SqlSessionUtil.getSqlSession();
        session.getMapper(SignMapper.class).del(uId);
        session.getMapper(CollectMapper.class).del(uId);
        session.getMapper(PraiseMapper.class).del(uId);
        ReplyMapper replyMapper = session.getMapper(ReplyMapper.class);
        replyMapper.delByUserId(uId);
        PostMapper postMapper = session.getMapper(PostMapper.class);
        List<Post> postList = postMapper.findPostByUserId(uId, -1, -1);
        for (Post post : postList) {
            replyMapper.delByPostId(post.getId());
        }
        postMapper.del(uId);
        userMapper = session.getMapper(UserMapper.class);
        boolean flag = userMapper.del(uId);
        session.commit();
        if (flag == true)
            return ResponseEntity.ok("删除成功");
        else
            session.rollback();
        return ResponseEntity.error("出错了");
    }


    public ResponseEntity editHeadImg(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(SysUtil.CURRENT_USER);
        int userId = user.getId();
        ResponseEntity fileUpload = FileUploadUtil.fileUpload(request);
        Map<String, String> map = (Map<String, String>) fileUpload.getData();
        //修改头像地址
        String fileName = map.get("fileName");
        user.setHeadImg(fileName);
        session = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        boolean flag = userMapper.editHeadImg(userId, fileName);
        session.commit();
        return fileUpload;
    }

    public ResponseEntity userStatus(int id,int userStatus) {
        session = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        boolean flag = userMapper.editStatus(id,userStatus);
        session.commit();
        if (!flag){
            session.rollback();
            return ResponseEntity.error("出错了");
        }
        return ResponseEntity.ok("修改成功！");
    }
}
